package com.qfedu.interceptor;

import com.qfedu.annotation.NoLoginCheck;
import com.qfedu.exception.CustomerException;
import com.qfedu.utils.JwtUtils;
import com.qfedu.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登录的权限判断
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //自定义注解  ThreadLocal

        //判断是否使用@NoLoginCheck注解
        //spring 会将控制层方法封装成HandlerMethod对象
        if (!(handler instanceof HandlerMethod)){
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //判断方法中是否使用了指定的注解
        boolean ret = method.isAnnotationPresent(NoLoginCheck.class);
        if (ret){
            return true;
        }


        String token = request.getHeader("Token");
        if (!StringUtils.hasLength(token)){
            throw new CustomerException(403,"请重新登录");
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer uid = (Integer)claims.get("uid");
            //向threadLocal中存入用户id
            UserUtils.setUid(uid);
        } catch (Exception e) {
            return true;
            //throw new CustomerException(403,"请重新登录");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.removeUid();
    }
}
